package com.zh.business.controller.web.user;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.AopLog;
import com.zh.zhbootcommon.domain.DPage;
import com.zh.zhbootcommon.domain.DResult;
import com.zh.zhbootcommon.entity.user.Permission;
import com.zh.business.service.web.user.IDPermissionService;
import com.zh.business.util.CommonUtils;
import com.zh.business.vo.web.PermissionTreeVo;
import com.zh.business.vo.web.PermissionVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 权限/菜单信息表 前端控制器
 * </p>
 *
 * @author JueDream
 * @since 2021-08-04
 */
@Slf4j
@RestController
@RequestMapping("/p/v1")
@Api(value = "权限/菜单")
@AopLog(type = "权限/菜单", stackTraceOnErr = true)
public class DPermissionController {

    @Autowired
    IDPermissionService permissionService;

    @ApiOperation(value = "权限/菜单列表查询接口")
    @PostMapping("/queryPermissionPage")
    public DResult queryPermissionPage(@RequestParam int page, @RequestParam int limit, @RequestParam String pName){
        Page<Permission> permissionPage = permissionService.queryPermissionPage(page, limit, pName);
        DPage<Permission> permissionDPage = DPage.to(permissionPage);
        return DResult.of(permissionDPage);
    }

    @ApiOperation(value = "权限/菜单列表查询接口(树形表格)")
    @PostMapping("/queryPermissionList")
    public DResult queryPermissionList(@RequestBody Map<String, Object> map){
        String pName = map.get("pName").toString();
        List<PermissionTreeVo> voList = new ArrayList<>();
        List<Permission> permissionList = permissionService.queryPermissionList(pName);
        Optional.ofNullable(permissionList).orElse(new ArrayList<>())
                .forEach(p -> {
                    voList.add(PermissionTreeVo.builder().id(p.getPId()).pid(p.getPParentId())
                    .title(p.getPName()).pType(p.getPType()).pRule(p.getPRule()).pReqType(p.getPReqType())
                    .pAvailable(p.getPAvailable()).pParentIds(p.getPParentIds())
                            .pUrl(p.getPUrl()).pRemark(p.getPRemark()).build());
                });
        return DResult.of(voList);
    }

    @ApiOperation(value = "权限/菜单列表查询接口(树形菜单-下拉)")
    @PostMapping("/queryPermissionTreeList")
    public DResult queryPermissionTreeList(@RequestBody Map<String, Object> map){
        String pName = map.get("pName").toString();
        Map<String, Object> resultMap = new HashMap<>();
        List<PermissionVo> voList = new ArrayList<>();
        List<Permission> permissionList = permissionService.queryPermissionList(pName);
        voList = CommonUtils.mergePermission(permissionService.queryMenu(), permissionList);
        resultMap.put("treeData", voList);
        resultMap.put("allData", permissionService.queryMenuAll());
        return DResult.of(resultMap);
    }

    @ApiOperation(value = "根据用户ID权限/菜单查询接口")
    @PostMapping("/queryMenuByUser")
    public DResult queryMenuByUser(@RequestBody Map<String, Object> map){
        List<PermissionVo> voList = new ArrayList<>();
        if (Objects.isNull(map.get("userId")) || StrUtil.isBlank(map.get("userId").toString())) {
            voList = CommonUtils.mergePermission(permissionService.queryMenu(), new ArrayList<>());
        }else{
            Integer userId = Integer.parseInt(map.get("userId").toString());
            voList = CommonUtils.mergePermission(permissionService.queryMenu(), permissionService.queryMenuByUser(userId, 1));
        }
        return DResult.of(voList);
    }


    @ApiOperation(value = "根据用户ID权限/菜单查询接口")
    @GetMapping("/queryMenuByUserId")
    public DResult queryMenuByUserId(@RequestParam Integer userId){
        if (userId <= 0) {
            return DResult.failed();
        }
        List<PermissionVo> voList = new ArrayList<>();
        // 主页左侧菜单 需要展示用户所属数据
        voList = CommonUtils.mergePermission(permissionService.queryMenuByUser(userId, 0),
                permissionService.queryMenuByUser(userId, 1));
        return DResult.of(voList);
    }


    @ApiOperation(value = "根据角色ID权限/菜单查询接口")
    @PostMapping("/queryMenuByRole")
    public DResult queryMenuByRole(@RequestBody Map<String, Object> map){
        /**
         * 展示的权限菜单数据是全部的
         * 属于该角色的选择状态，不是则不选中
         */
        List<Integer> roleIds = new ArrayList<>();
        String roleIdStr = map.get("roleIds").toString();
        if (StrUtil.isNotBlank(roleIdStr)){
            roleIds = Arrays.asList(roleIdStr.split(",")).stream()
                    .map(s -> Integer.valueOf(s.trim()))
                    .collect(Collectors.toList());
        }
        List<PermissionVo> voList = new ArrayList<>();
        if (roleIds.size() > 0) {
            voList = CommonUtils.mergePermission(permissionService.queryMenu(), permissionService.queryMenuByRole(roleIds));
        }else{
            voList = CommonUtils.mergePermission(permissionService.queryMenu(), new ArrayList<>());
        }
        return DResult.of(voList);
    }

    @ApiOperation(value = "权限/菜单查询所有接口")
    @GetMapping("/queryPermissionTreeList")
    public DResult queryPermissionAll(){
        return DResult.of(permissionService.queryMenuAll());
    }


    @ApiOperation(value = "权限/菜单查询单个接口")
    @GetMapping("/queryPermissionOne")
    public DResult queryPermissionOne(@RequestParam Integer pId){
        return DResult.of(permissionService.queryPermissionOne(pId));
    }

    @Transactional
    @ApiOperation(value = "权限/菜单编辑接口")
    @PostMapping("/saveOrUpdate")
    public DResult saveOrUpdate(@RequestBody Permission permission) {
        boolean flag = false;
        if (permission.getPId() < 0) {
            // 新增
            flag = permissionService.save(permission);
        } else if (permission.getPId()  > 0) {
            // 更新
            flag = permissionService.updateById(permission);
        }
        return DResult.of(flag);
    }

    @ApiOperation(value = "权限/菜单删除接口")
    @DeleteMapping("/delete")
    public DResult delete(@RequestParam Integer pId){
        boolean flag = false;
        if (pId > 0) {
            flag = permissionService.removePermission(pId);
        }
        return DResult.of(flag);
    }


}
